package 代码随想录_补充题目;

/**
 * @author zx
 * @create 2023-02-10 20:11
 */
public class 寻找数组的中心下标_724 {
    /**
     * 1.遍历一遍求出总和sum
     * 2.遍历第二遍求中心索引左半和leftSum
     *   同时根据sum和leftSum计算中心索引右半和rightSum
     *   判断leftSum和rightSum是否相同
     */
    public int pivotIndex(int[] nums) {
        int sum = 0;
        for(int i = 0;i < nums.length;i++){
            sum += nums[i];
        }
        int leftSum = 0,rightSum = 0;
        for(int i = 0;i < nums.length;i++){
            leftSum += nums[i];
            //leftSum里面已经有nums[i],所以右边也加上
            rightSum = sum - leftSum + nums[i];
            if(leftSum == rightSum){
                return i;
            }
        }
        return -1;
    }
}
